package com.baidu.shop.business.impl;

import com.baidu.shop.base.BaseApiService;
import com.baidu.shop.base.Result;
import com.baidu.shop.business.OrderService;
import com.baidu.shop.config.RedisConfig;
import com.baidu.shop.dto.OrderDTO;
import com.baidu.shop.config.JwtConfig;
import com.baidu.shop.dto.Car;
import com.baidu.shop.dto.OrderInfo;
import com.baidu.shop.dto.UserInfo;
import com.baidu.shop.entity.OrderDetailEntity;
import com.baidu.shop.entity.OrderEntity;
import com.baidu.shop.entity.OrderStatusEntity;
import com.baidu.shop.mapper.OrderDetailMapper;
import com.baidu.shop.mapper.OrderMapper;
import com.baidu.shop.mapper.OrderStatusMapper;
import com.baidu.shop.redis.repository.RedisRepository;
import com.baidu.shop.status.HTTPStatus;
import com.baidu.shop.utils.BaiduBeanUtil;
import com.baidu.shop.utils.IdWorker;
import com.baidu.shop.utils.JwtUtils;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @ClassName: OrderServiceImpl
 * @Author: User
 * @date: 2020.10.21 14:01
 * @version: 1.0
 */
@RestController
public class OrderServiceImpl extends BaseApiService implements OrderService {
    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderDetailMapper orderDetailMapper;

    @Resource
    private OrderStatusMapper orderStatusMapper;

    @Resource
    private JwtConfig jwtConfig;

    @Resource
    private RedisRepository redisRepository;

    @Resource
    private IdWorker idWorker;

    public static String GOODS_CAR_PRE = "goods_car_";

    @Override
    public Result<OrderInfo> getOrderInfoByOrderId(Long orderId) {
        //根据orderId查询订单表 用beanCopy处OrderInfo
        OrderEntity orderEntity = orderMapper.selectByPrimaryKey(orderId);
        OrderInfo orderInfo = BaiduBeanUtil.copyProperties(orderEntity, OrderInfo.class);
        //根据orderId查询orderDetail详情表
        Example example = new Example(OrderDetailEntity.class);
        example.createCriteria().andEqualTo("orderId", orderInfo.getOrderId());
        List<OrderDetailEntity> orderDetailEntities = orderDetailMapper.selectByExample(example);
        orderInfo.setOrderDetailList(orderDetailEntities);
        //根据orderId查询订单详情表
        OrderStatusEntity orderStatusEntity = orderStatusMapper.selectByPrimaryKey(orderInfo.getOrderId());
        orderInfo.setOrderStatusEntity(orderStatusEntity);
        return this.setResultSuccess(orderInfo);
    }

    @Override
    public Result<String> createOrder(OrderDTO orderDTO, String token) {
        Long orderId = idWorker.nextId();
        try {
            UserInfo infoFromToken = JwtUtils.getInfoFromToken(token, jwtConfig.getPublicKey());
            //生成订单
            OrderEntity orderEntity = new OrderEntity();
            orderEntity.setOrderId(orderId); //订单id
            orderEntity.setPaymentType(orderDTO.getPayType());//支付类型
            Date date = new Date();
            orderEntity.setCreateTime(date);//创建时间
            orderEntity.setUserId(infoFromToken.getId().toString());//用户id

            orderEntity.setBuyerMessage("很强"); //买家留言
            orderEntity.setBuyerNick(infoFromToken.getUsername());//买家昵称
            orderEntity.setBuyerRate(0);//买家是否评价
            orderEntity.setInvoiceType(1);//发票类型
            orderEntity.setSourceType(1);//订单来源

            //订单详情
            String skuIds = orderDTO.getSkuIds();
            //创建总价格
            List<Long> totalPrice = Arrays.asList(0L);
            List<OrderDetailEntity> OrderDetails = Arrays.asList(skuIds.split(",")).stream().map(skuId -> {
                Car hash = redisRepository.getHash(GOODS_CAR_PRE + infoFromToken.getId(), skuId, Car.class);
                OrderDetailEntity orderDetailEntity = new OrderDetailEntity();
                orderDetailEntity.setOrderId(orderId);
                orderDetailEntity.setImage(hash.getImage());
                orderDetailEntity.setNum(hash.getNum());
                orderDetailEntity.setOwnSpec(hash.getOwnSpec());
                orderDetailEntity.setPrice(hash.getPrice());
                orderDetailEntity.setSkuId(hash.getSkuId());
                orderDetailEntity.setTitle(hash.getTitle());
                totalPrice.set(0, (hash.getPrice() * hash.getNum())+totalPrice.get(0));
                return orderDetailEntity;
            }).collect(Collectors.toList());

            orderEntity.setTotalPay(totalPrice.get(0));//设置总金额
            orderEntity.setActualPay(totalPrice.get(0));//实付金额

            //订单状态
            OrderStatusEntity orderStatusEntity = new OrderStatusEntity();
            orderStatusEntity.setCreateTime(date);
            orderStatusEntity.setOrderId(orderId);
            orderStatusEntity.setStatus(1);//订单状态,未交付
            //入库
            orderMapper.insertSelective(orderEntity);
            orderDetailMapper.insertList(OrderDetails);
            orderStatusMapper.insertSelective(orderStatusEntity);
            //删除redis中的数据
            Arrays.asList(skuIds.split(",")).stream().forEach(skuId->{

                redisRepository.delHash(GOODS_CAR_PRE+infoFromToken.getId(), skuId);
            });
            //此时要保证redis和myqsl双写一致性
            //更新库存-->用户已经下单了,这个时候减库存
        } catch (Exception e) {
            e.printStackTrace();
            return this.setResultError("后台异常");
        }


        System.out.println("=======");
        return this.setResult(HTTPStatus.OK, "", orderId.toString());
    }
}
